package cn.youframe.frame.log;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.InputStream;

/**
 * User: Administrator
 * DateTime: 12-4-25: 下午3:25
 */
public class LogConfigListener implements ServletContextListener {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    private static final String CONFIG_LOCATION = "LogConfigLocation";
    // -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext sc=sce.getServletContext();
        String logbackConfigLocation = sce.getServletContext().getInitParameter(CONFIG_LOCATION);
        InputStream in=sc.getResourceAsStream(logbackConfigLocation);
        try {
            LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
            loggerContext.reset();
            JoranConfigurator joranConfigurator = new JoranConfigurator();
            joranConfigurator.setContext(loggerContext);
            joranConfigurator.doConfigure(in);
            logger.info("loaded log configure file from {}", logbackConfigLocation);
        }
        catch (JoranException e) {
            logger.error("can loading log configure file from " + logbackConfigLocation, e);
        }
    }

    public void contextDestroyed(ServletContextEvent sce) {
    }

}
